import { MaterialIcons } from '@expo/vector-icons';
import React from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';

interface PopoverItem {
  icon: string;
  label: string;
  onPress: () => void;
}

interface ContextPopoverProps {
  /** 是否显示弹出层 */
  visible: boolean;
  /** 弹出层显示位置 */
  position: { x: number; y: number };
  /** 画布容器尺寸 */
  containerSize: { width: number; height: number };
  /** 弹出层选项列表 */
  items: PopoverItem[];
  /** 点击背景遮罩的回调 */
  onBackdropPress: () => void;
}

const POPOVER_WIDTH = 200;
const POPOVER_ITEM_HEIGHT = 48;
const POPOVER_PADDING = 8;
const OFFSET_DISTANCE = 16;

/**
 * 上下文弹出层组件
 * 支持智能定位，确保弹出层不会超出容器边界
 */
export default function ContextPopover({
  visible,
  position,
  containerSize,
  items,
  onBackdropPress,
}: ContextPopoverProps) {
  if (!visible) return null;

  /**
   * 计算弹出层的最佳显示位置
   * @param clickPosition 点击位置
   * @param containerSize 容器尺寸
   * @returns 调整后的位置和变换参数
   */
  const calculatePopoverPosition = (
    clickPosition: { x: number; y: number },
    containerSize: { width: number; height: number }
  ) => {
    const popoverHeight = items.length * POPOVER_ITEM_HEIGHT + POPOVER_PADDING * 2;
    
    let finalX = clickPosition.x;
    let finalY = clickPosition.y;
    let translateX = -POPOVER_WIDTH / 2; // 默认水平居中
    let translateY = OFFSET_DISTANCE; // 默认显示在点击位置下方

    // 水平方向边界检查
    if (clickPosition.x - POPOVER_WIDTH / 2 < 0) {
      // 左边界溢出，左对齐
      translateX = 0;
      finalX = Math.max(0, clickPosition.x);
    } else if (clickPosition.x + POPOVER_WIDTH / 2 > containerSize.width) {
      // 右边界溢出，右对齐
      translateX = -POPOVER_WIDTH;
      finalX = Math.min(containerSize.width, clickPosition.x);
    }

    // 垂直方向边界检查
    if (clickPosition.y + OFFSET_DISTANCE + popoverHeight > containerSize.height) {
      // 下边界溢出，显示在点击位置上方
      translateY = -popoverHeight - OFFSET_DISTANCE;
    }

    // 确保弹出层不会超出上边界
    if (clickPosition.y + translateY < 0) {
      translateY = -clickPosition.y;
    }

    return {
      x: finalX,
      y: finalY,
      translateX,
      translateY,
    };
  };

  const popoverPosition = calculatePopoverPosition(position, containerSize);

  return (
    <View style={styles.backdrop} pointerEvents="box-none">
      <View
        style={[
          styles.popover,
          {
            position: 'absolute',
            left: popoverPosition.x,
            top: popoverPosition.y,
            transform: [
              { translateX: popoverPosition.translateX },
              { translateY: popoverPosition.translateY },
            ],
          },
        ]}
      >
        {items.map((item, index) => (
          <TouchableOpacity
            key={index}
            style={[
              styles.popoverItem,
              index === items.length - 1 && styles.lastPopoverItem,
            ]}
            onPress={item.onPress}
          >
            <MaterialIcons name={item.icon as any} size={24} color="#333" />
            <Text style={styles.popoverText}>{item.label}</Text>
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  backdrop: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'transparent',
  },
  popover: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: POPOVER_PADDING,
    width: POPOVER_WIDTH,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
    overflow: 'hidden',
    zIndex: 2,
  },
  popoverItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#eee',
    height: POPOVER_ITEM_HEIGHT,
  },
  lastPopoverItem: {
    borderBottomWidth: 0,
  },
  popoverText: {
    marginLeft: 12,
    fontSize: 16,
    color: '#333',
  },
});